package com.ljph.jfinal.base;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.NestedTransactionHelpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by yuzhou on 16/8/11.
 */
public class BaseService {

  private static final Logger _log = LoggerFactory.getLogger(BaseService.class);

  protected boolean throwError = false;

  public void setThrowError(boolean throwError) {
    this.throwError = throwError;
  }

  private void throwErrMsg() {
    if(throwError) {
      throw new RuntimeException(lastErrMsg);
    }
  }

  protected String lastErrMsg = null;

  public String getLastErrMsg() {
    return lastErrMsg;
  }

  public void setLastErrMsg(String lastErrMsg, Exception e) {
    if (e instanceof NestedTransactionHelpException) {
      if (StrKit.notBlank(lastErrMsg)) {
        _log.error("当前事务作为内部事务调用时失败, 出错原因为：{}，忽略：{}", this.lastErrMsg, lastErrMsg, e);
        return;
      }
    }

    if (e instanceof ActiveRecordException && e.getMessage().contains("Duplicate entry")) {
      this.lastErrMsg = lastErrMsg + "：不能保存重复的数据记录"; //TODO: 更加精确化这条提示
    } else {
      this.lastErrMsg = lastErrMsg + (StrKit.notBlank(e.getMessage()) ? (": " + e.getMessage()) : "");
    }

    _log.error("{}({})", lastErrMsg, this.getClass().getName(), e);
    throwErrMsg();
  }

  public void setLastErrMsg(String lastErrMsg) {
    setLastErrMsg(lastErrMsg, "");
  }

  public void setLastErrMsg(Exception e) {
    String msg = "数据异常";
    setLastErrMsg(msg, e);
  }

  public void setLastErrMsg(String lastErrMsg, String detail) {
    setLastErrMsg(lastErrMsg, new RuntimeException(detail));
  }
}
